package notifier.view;

import chat.view.dialogs.ContactListDialog;
import chat.view.menus.ClientsMenu;
import icon.tester.IconTesterDialog;
import notifier.exceptions.SystemTrayIsNotSupportedException;
import notifier.exceptions.TrayIconCouldNotBeAddedException;
import notifier.view.menus.AboutItem;
import notifier.view.menus.ExitItem;
import notifier.view.menus.services.ServicesMenu;
import pt.record.view.menus.RecordMenu;
import pt.zero.zero.view.ZeroZeroMenu;
import swing.DialogMenuItem;
import swing.Images;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class SysTray implements Runnable {
    private final SystemTray systemTray;
    private final TrayIcon trayIcon;
    private final ContactListDialog contactListDialog = new ContactListDialog();

    public SysTray() {
        //Check the SystemTray support
        if (!SystemTray.isSupported())
            throw new SystemTrayIsNotSupportedException();

        trayIcon = new TrayIcon(Images.loadImage(SysTray.class, "images/bulb.gif"));
        systemTray = SystemTray.getSystemTray();

        final PopupMenu popupMenu = new PopupMenu();
        trayIcon.addMouseListener(new MouseAdapter() {
            public void mouseReleased(MouseEvent e) {
                if (SwingUtilities.isRightMouseButton(e)) {
                    popupMenu.setLocation(e.getX(), e.getY());
                    popupMenu.setInvoker(popupMenu);
                    popupMenu.setVisible(true);
                }
            }
        });

        try {
            systemTray.add(trayIcon);
        } catch (AWTException e) {
            throw new TrayIconCouldNotBeAddedException(e);
        }

        trayIcon.addActionListener(e -> contactListDialog.setVisible(true));
    }

    @Override
    public void run() {
    }

    private class PopupMenu extends JPopupMenu {
        /**
         *
         */
        private static final long serialVersionUID = -8953775325172237112L;

        private PopupMenu() {
            //Add components to popup menu
            add(new DialogMenuItem(contactListDialog));
            addSeparator();
            add(new DialogMenuItem(IconTesterDialog.class, trayIcon));
            addSeparator();
            add(new ClientsMenu());
            add(new ServicesMenu());
            add(new ZeroZeroMenu());
            add(new RecordMenu());
            addSeparator();
            add(new AboutItem());
            add(new ExitItem(systemTray, trayIcon));
        }
    }

    private class TrayIcon extends java.awt.TrayIcon {

        public TrayIcon(Image image) {
            super(image);
            setImageAutoSize(true);
            setToolTip("Sun TrayIcon");
        }
    }
}
